package com.ld.shieldsb.common.web.tag;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.jsp.JspException;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @ClassName: SwitchoputTag
 * @Description: 用于转换显示值 如0男1女 0=男|1=女
 * @author 吕凯
 * @date 2012-11-23 上午11:14:41
 *
 */
@EqualsAndHashCode(callSuper = false)
@Data
@Slf4j
public class SwitchOputTag extends TagSupportBasicTag {

    /**
     * 
     */
    private static final long serialVersionUID = 3896122183574339789L;
    /**
     * 待转换的值
     */
    private String value;
    /**
     * 取值范围,|分隔不同组的值=分隔键值对 如：0=男|1=女|default=男
     */
    private String data;

    @Override
    public int doEndTag() throws JspException {
        try {
            String[] dataStrs = data.split("\\|");
            Map<String, String> map = new HashMap<>();
            if (dataStrs != null && dataStrs.length > 0) {
                for (int i = 0; i < dataStrs.length; i++) {
                    String[] mapKVs = dataStrs[i].split("=");
                    if (mapKVs.length == 1) { // 没有等号的处理为默认值
                        map.put("default", mapKVs[0]);
                    } else if (mapKVs.length == 2) {
                        String mapKey = mapKVs[0];
                        String mapValue = mapKVs[1];
                        map.put(mapKey, mapValue);
                    }
                }
            }
            if (!map.isEmpty()) {
                value = (String) map.get(value);
            }
            if (value == null) {
                value = map.get("default") == null ? "" : (String) map.get("default");
            }
            setAttrOrOut(pageContext.getOut(), value);
            log.debug("调用输出转换标签：" + value);
        } catch (IOException e) {
            log.error("", e);
        }
        return SKIP_BODY;
    }

    @Override
    public int doStartTag() throws JspException {
        return EVAL_PAGE;
    }
}
